package com.gitee.ly.nami;

import org.noear.nami.Filter;
import org.noear.nami.NamiBuilder;
import org.noear.nami.NamiConfiguration;
import org.noear.nami.NamiManager;
import org.noear.nami.annotation.NamiClient;
import org.noear.solon.Utils;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.util.PathUtil;

public final class NamiConfigurationLocalFix implements NamiConfiguration {

    private NamiConfiguration custom;
    private AppContext context;

    public NamiConfigurationLocalFix(AppContext context) {
        this.context = context;

        //
        //如果有定制的NamiConfiguration, 则用之
        //
        context.getBeanAsync(NamiConfiguration.class, (bean) -> {
            custom = bean;
        });

        //订阅拦截器
        context.subBeansOfType(Filter.class, it -> {
            NamiManager.reg(it);
        });
    }

    @Override
    public void config(NamiClient client, NamiBuilder builder) {
        if (Utils.isEmpty(client.name())) {
            return;
        }
        String localfixUrl = this.context.cfg().get(client.name() + ".url");
        //serviceName -> url (local fix )
        builder.url(PathUtil.joinUri(localfixUrl, client.path()));

        //尝试自定义
        if (custom != null) {
            custom.config(client, builder);
        }
    }
}
